package io.iec.edp.caf.boot.starter.middleware.spi.utils;

import io.iec.edp.caf.commons.runtime.CafEnvironment;
import io.iec.edp.caf.commons.runtime.env.enums.StartupMode;
import io.iec.edp.caf.middleware.spi.ClassUrlResolver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;

import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.ServiceLoader;

@Slf4j
public class ClassLoaderResolverUtils {

    private static Map<String, ClassUrlResolver> ClassLoaderResolverMap = new HashMap();

    private static ClassUrlResolver currentClassLoaderResolver = null;

    static {
        ServiceLoader<ClassUrlResolver> resolvers = ServiceLoader.load(ClassUrlResolver.class);
        for (ClassUrlResolver resolver : resolvers) {
            ClassLoaderResolverMap.put(resolver.getId(), resolver);
        }

        if (CafEnvironment.getStartupMode() == StartupMode.Parallel) {
            currentClassLoaderResolver = ClassLoaderResolverMap.get("1");
        } else {
            currentClassLoaderResolver = ClassLoaderResolverMap.get("0");
        }
        Assert.notNull(currentClassLoaderResolver, "[currentClassLoaderResolver] is null, please check.");
    }


   public static void addUrl(ClassLoader cl, URL[] urls){
       if (log.isDebugEnabled()) {
           log.debug("CurrentClassLoaderResolver type [{}].", currentClassLoaderResolver.getClass().getName());
       }
       currentClassLoaderResolver.addUrl(cl,urls);
   }


}
